{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "366e469a-01f8-43f7-b5f8-a306c4671061",
   "metadata": {},
   "source": [
    "## 使用文件加载专用chains"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d7d80c1-bfae-474d-a95c-206d02a4cd88",
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install numexpr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b6bf662-c16d-4fbe-b615-98feea718ff6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains import load_chain\n",
    "\n",
    "# https://github.com/hwchase17/langchain-hub\n",
    "# https://smith.langchain.com/hub\n",
    "chain = load_chain(\"lc://chains/llm-math/chain.json\")\n",
    "\n",
    "print(chain.run(\"2+6等于几?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85750dd7-7726-4f4e-bba3-f24b08c517e3",
   "metadata": {},
   "source": [
    "## 自定义链\n",
    "当通用链不满足的时候，可以自行构建来实现特定的目的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "441c7c9b-11a3-48e8-af04-ce405fd43792",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List, Dict, Any, Optional\n",
    "from langchain.callbacks.manager import (\n",
    "    CallbackManagerForChainRun\n",
    ")\n",
    "from langchain.chains.base import  Chain\n",
    "from langchain.prompts.base import BasePromptTemplate\n",
    "from langchain.base_language import  BaseLanguageModel\n",
    "\n",
    "class wiki_article_chain(Chain):\n",
    "    \"\"\"开发一个wiki文章生成器\"\"\"\n",
    "    prompt:BasePromptTemplate\n",
    "    llm:BaseLanguageModel\n",
    "    out_key:str=\"text\"\n",
    "\n",
    "    @property\n",
    "    def input_keys(self) -> List[str]:\n",
    "        \"\"\"将返回Prompt所需的所有键\"\"\"\n",
    "        return self.prompt.input_variables\n",
    "    \n",
    "    @property\n",
    "    def output_keys(self) -> List[str]:\n",
    "        \"\"\"将始终返回text键\"\"\"\n",
    "        return [self.out_key]\n",
    "    \n",
    "    def _call(self, inputs:Dict[str,Any], run_manager:Optional[CallbackManagerForChainRun]=None) -> Dict[str,Any]:\n",
    "        \"\"\"运行链\"\"\"\n",
    "        # 生成提示词\n",
    "        prompt_value = self.prompt.format_prompt(**inputs)\n",
    "        #print(\"prompt_value:\",prompt_value)\n",
    "        # 调用大模型\n",
    "        response = self.llm.generate_prompt(\n",
    "            [prompt_value],callbacks=run_manager.get_child() if run_manager else None\n",
    "        )\n",
    "        #print(\"response:\",response)\n",
    "        if run_manager:\n",
    "            run_manager.on_text(\"wiki article is written\")\n",
    "        return {self.out_key:response.generations[0][0].text}\n",
    "    \n",
    "    @property\n",
    "    def _chain_type(self) -> str:\n",
    "        \"\"\"链类型\"\"\"\n",
    "        return \"wiki_article_chain\"\n",
    "       "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98a4e3fd-2ad2-4d2c-90fd-f33bafa3bac2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import  ChatOpenAI\n",
    "from langchain.prompts import  PromptTemplate\n",
    "\n",
    "chain = wiki_article_chain(\n",
    "    prompt=PromptTemplate(\n",
    "        template=\"写一篇关于{topic}的维基百科形式的文章\",\n",
    "        input_variables=[\"topic\"]\n",
    "    ),\n",
    "    llm=ChatOpenAI(\n",
    "        temperature=0\n",
    "    ),\n",
    ")\n",
    "\n",
    "result = chain.run({\"topic\":\"降本增效\"})\n",
    "print(result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (langchain)",
   "language": "python",
   "name": "langchain-env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
